package com.electric.qrapp.utils.data

import com.electric.qrapp.utils.function.GsonUtils
import com.electric.qrapp.utils.function.deleteFile
import com.electric.qrapp.utils.system.Constants.File.MAX_FILE_CACHE
import com.electric.qrapp.utils.system.showLog
import com.google.gson.reflect.TypeToken
import kotlinx.coroutines.flow.first
import rxhttp.wrapper.utils.GsonUtil
import javax.inject.Inject

/**
 *@author created by WA03675
 *@date  2021-09-23 14:03
 *@des 数据管理类
 */
class DataManager @Inject constructor() {
    object SPKey {

        //扫码文件保存
        const val FILES_CACHE = "files_cache"

    }


    companion object {

        //获取 存储的文档信息
        suspend fun getCacheFileList(): MutableList<String> {
            val datas = DataStoreUtils.getData(SPKey.FILES_CACHE, "").first()
            return if (datas.isNullOrBlank()) {
                mutableListOf()
            } else {
                return GsonUtil.fromJson(datas, object :
                    TypeToken<MutableList<String>>() {}.type)
            }
        }


        suspend fun isHaveFile(fileName: String): Boolean {
            return getCacheFileList().contains(fileName)
        }

        //存储的文档信息
        suspend fun setCacheFileList(path: String) {
            with(getCacheFileList()) {

                if (this.contains(path)) {
                    this.remove(path)
                }

                add(0, path)

                forEachIndexed { index, item ->
                    if (index > MAX_FILE_CACHE - 1) {
                        deleteFile(item)
                    }
                }
                DataStoreUtils.putSyncData(
                    SPKey.FILES_CACHE,
                    GsonUtils.gsonString(if (size > MAX_FILE_CACHE) take(MAX_FILE_CACHE) else this)
                )
            }
        }
    }
}


